<?php

namespace goosh;

class search

{
  protected
    $query,
    $api;

  public function __construct
  (
    $query
  )
  
  {
    $this->query=$query;
    
    $this->api=ini::get('api');
    $this->switch=ini::get('switch');
    
    if($this->api=='custom')
    return $this->custom();
    
    if($this->api=='web')
    
    {
      $last=new \DateTime(ini::get('switch'));
      $now=new \DateTime;
      
      $diff=(($now->getTimeStamp()-$last->getTimeStamp())/(60*60));
      
      if($diff>24)
      
      {
        ini::set('api','custom');
        
        return $this->custom();
      }
      
      return $this->web();
    }
  }
  
  protected function custom()
  
  {
    $url=ini::get('url');
    $key=ini::get('key');
    $cx=ini::get('cx');
    $num=ini::get('num');
    
    $curl=`curl '$url?key=$key&cx=$cx&q=$this->query&num=$num' 2> /dev/null`;

    $response=json_decode($curl);

    if(is_null($response))
    throw new gooshException('response from google was not understood');

    if(isset($response->error))

    switch($response->error->message)

    {
      default:
      
        throw new gooshException('API died');
      
      break;
      
      case'Daily Limit Exceeded':
      
        return $this->switchToWeb();
      
      break;
    }

    if(!isset($response->items))

    {
      if(isset($response->queries->request))
      
      {
        if($response->queries->request[0]->totalResults==0)
        println('No results found');
      }
    }

    else

    {
      $i=1;
      foreach($response->items as $item)
      $this->show($i++,$item->title,$item->snippet,$item->link);
    }
  }
  
  protected function web()
  
  {
    $url=ini::get('url2');
    $referer=ini::get('referer');
    $key=ini::get('key2');
    
    $curl=`curl -e $referer '$url&q=$this->query&key=$key' 2> /dev/null`;
    
    $response=json_decode($curl);
    
    if(is_null($response))
    throw new gooshException('Could not read response from Google');
    
    $i=1;
    
    foreach($response->responseData->results as $result)
    $this->show($i++,$result->title,$result->content,$result->url);
  }
  
  public function show($number,$title,$content,$url)
  
  {
    $title=strip_tags($title);
    $content=preg_replace('/\s\s+/','
  ',strip_tags($content));
  
    println("
  $number) $title | $url
  
  $content
  ");
  }
  
  public function switchToWeb()
  
  {
    ini::set('api','web');
    
    $this->web();
  }
}
